package io.github.eiot.utils;

/**
 * created by wang007 on 2025/10/10
 */
public class SubByteUtil {

    /**
     * read sub byte from source.
     *
     * eg: 000110000. read 11 bit. readSubByte(v, 4, 2)
     *
     * @param source source
     * @param index  index
     * @param length length
     * @return read result
     */
    public static int read(long source, int index, int length) {
        long v = source;
        if (index > 0) {
            v = source >>> index;
        }
        // eg bitLength = 2, 保留 2位， 左移 2 位，之后 100 -1 = 11
        long mark = (1L << length) - 1;
        return (int) (mark & v);
    }

    /**
     * write value into source.
     * eg: source: 000110000. write 3, index 1, length 3, result: 000111110
     *
     * @param source source
     * @param value  value
     * @param index  index
     * @param length length
     * @return result
     */
    public static long write(long source, int value, int index, int length) {
        long l = value;
        //long mark = 1L << bitLength;
        if (index > 0) {
            l = l << index;
        }
        return source | l;
    }

}
